/**
 * 调用方式 this.$httpPost(url,params,function(res){});
 * @param {Object} Vue
 * @param {Object} option
 */
import {
    DesEncode,
    DesDecode
} from '@/common/jeesite4_des.js';
exports.install = function(Vue, option) {

    /**
     * 群晖get封装
     * @param {Object} url
     * @param {Object} data
     */
    Vue.prototype.$get = function(url, data) {
        if (this.$config.sid) {
            data._sid = this.$config.sid
        }
        return new Promise((resolve, reject) => {
            uni.request({
                url: this.$config.host + url,
                data: data,
                header: {
                    'Accept': 'application/json',
                    'Content-Type': 'application/x-www-form-urlencoded', //自定义请求头信息
                    // #ifndef H5
                    'Cookie': this.$config.cookie,
                    // #endif
                },

                method: "GET",
                success: (response) => {
                    if (response.statusCode === 200) {
                        resolve(response.data)
                    } else {
                        reject(response)
                    }
                },
                fail: (error) => {
                    if (error && error.response) {
                        reject(error.response)
                        showError(error.response);
                    }
                },


            });
        })

    }

    /**
     * 封装群晖api调用方法
     * @param {Object} apiName api名称
     * @param {Object} data 数据
     */
    Vue.prototype.$Api = function(apiName, data) {
        let api = this.$config.api[apiName]
        if (!api) {
            this.$config.api = uni.getStorageSync('QH_API')
            console.log('[信息]重新查找api', apiName, this.$config.api)
            api = this.$config.api[apiName]
        }
        if (api) {
            data.version = api.maxVersion;
            data.api = apiName;
            return this.$post('/webapi/' + api.path, data);
        } else {
            return new Promise((resolve, reject) => {
                console.warn('[警告]未找到对应的api[' + apiName + ']', this.$config.api)
                reject('未找到对应的api[' + apiName + ']')
            })
        }
    }

    /**
     * 获取音乐封面
     * @param {Object} musicId
     */
    Vue.prototype.$getMusicCoverUrl = async function(musicId) {
        const apiName = 'SYNO.AudioStation.Cover'
        const api = this.$config.api[apiName]
        const key = 'loadCoverImage:'
        if (api) {
            let url = '/webapi/' + api.path +
                '?api=' + apiName +
                '&id=' + musicId +
                '&_dc=' + new Date().getTime();
            return new Promise((resolve, reject) => {
                const coverImg = uni.getStorageSync(key + musicId)
                if (coverImg) {
                    try {
                        setTimeout(function() {
                            // console.debug('[信息]发现缓存图片', musicId, coverImg.length)
                            resolve(coverImg)
                        }, 0)
                        return
                    } catch (e) {
                        // reject(e)
                        console.warn(musicId, coverImg, e)
                    }
                }
                uni.request({
                    url: this.$config.host + url,
                    data: {
                        _sid: this.$config.sid,
                        api: apiName,
                        output_default: true,
                        is_hr: false,
                        version: 3,
                        library: 'shared',
                        method: 'getsongcover',
                        view: 'default',
                        id: musicId,
                        Synotoken: this.$config.synotoken,
                    },
                    header: {
                        'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
                        'X-SYNO-HASH': 'uniapp',
                        'X-SYNO-TOKEN': this.$config.synotoken,
                        // #ifndef H5
                        'Cookie': this.$config.cookie,
                        // #endif
                    },
                    responseType: 'arraybuffer',
                    method: "POST",
                    success: (response) => {
                        // console.log('[信息]', response.header['content-type'], response)
                        if (response.statusCode === 200) {

                            // console.log(img, url)
                            // #ifdef APP
                            const base64 = 'data:' + response.header['content-type'] +
                                ';base64,' + uni
                                .arrayBufferToBase64(response.data);
                            uni.setStorageSync(key + musicId, base64);
                            // console.debug('[信息]加载在线图片', musicId)
                            resolve(base64)
                            return
                            // #endif
                            // #ifdef H5
                            const img = new Blob([response.data], {
                                type: response.header['content-type']
                            })
                            const url = URL.createObjectURL(img);
                            let binary = '';
                            let bytes = new Uint8Array(response.data);
                            for (let i = 0; i < bytes.byteLength; i++) {
                                binary += String.fromCharCode(bytes[i]);
                            }
                            const base64 = 'data:' + response.header['content-type'] +
                                ';base64,' + window.btoa(
                                    binary);
                            //h5上使用缓存会导致localStrong很快占满
                            // uni.setStorageSync(key + musicId, base64);
                            // console.debug('[信息]加载在线图片', musicId)
                            resolve(url)
                            // #endif

                        } else {
                            reject(response)
                        }
                    },
                    fail: (error) => {
                        console.error('[错误]图片加载错误', error)
                    },
                });
            })
        } else {
            return ''
        }
    }

    /**
     * 获取音乐地址
     * @param {Object} musicId
     */
    Vue.prototype.$getMusicUrl = async function(musicId, musicName) {
        let _this = this
        const apiName = 'SYNO.AudioStation.Stream'
        const api = this.$config.api[apiName]
        const key = 'loadMusicUrl:'
        if (api) {
            let params = {
                api: apiName,
                version: api.maxVersion,
                method: 'stream',
                id: musicId,
                _dc: new Date().getTime(),
                _sid: this.$config.sid
            }
            // let url = this.$config.host + '/webapi/' + api.path + '?'
            // for (let key in params) {
            //     url += key + '=' + params[key] + '&'
            // }
            // url = url.substr(0, url.length - 1)
            // return url
            return new Promise((resolve, reject) => {
                //找缓存
                const tmpBase64 = uni.getStorageSync(key + musicId);
                if (tmpBase64) {
                    setTimeout(function() {
                        resolve(tmpBase64)
                    }, 1)
                    return
                }
                // #ifdef H5
                // uni.showLoading({
                //     title: '音乐加载中...'
                // })
                uni.request({
                    url: this.$config.host + '/webapi/' + api.path,
                    data: params,
                    header: {
                        'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
                        'X-SYNO-HASH': 'uniapp',
                        'X-SYNO-TOKEN': this.$config.synotoken
                    },
                    responseType: 'arraybuffer',
                    method: "POST",
                    complete() {
                        uni.hideLoading()
                    },
                    success: (response) => {
                        console.log('[信息]', response.header['content-type'], response)
                        if (response.statusCode === 200) {

                            // console.log(img, url)
                            // #ifdef APP
                            const base64 = 'data:' + response.header['content-type'] +
                                ';base64,' +
                                uni
                                .arrayBufferToBase64(response.data);
                            if (_this.$config && _this.$config.cacheMusic) {
                                uni.setStorageSync(key + musicId, base64);
                            }
                            resolve(base64)
                            return
                            // #endif
                            // #ifdef H5
                            const img = new Blob([response.data], {
                                type: response.header['content-type']
                            })
                            const url = URL.createObjectURL(img);
                            let binary = '';
                            let bytes = new Uint8Array(response.data);
                            for (let i = 0; i < bytes.byteLength; i++) {
                                binary += String.fromCharCode(bytes[i]);
                            }
                            const base64 = 'data:' + response.header['content-type'] +
                                ';base64,' + window.btoa(
                                    binary);
                            resolve(base64)
                            // #endif

                        } else {
                            reject(response)
                        }
                    },
                    fail: (error) => {
                        console.error('[错误]音频加载错误', error)
                    },
                });
                // #endif
                // #ifndef H5
                 //保存音乐的地址
                let savePath = plus.io.convertLocalFileSystemURL('../doc/uniapp_save')
                let savedFilePath = savePath + '/' + musicName;
                // console.log('[信息]查找本地文件', savedFilePath)
                plus.io.resolveLocalFileSystemURL(savedFilePath,
                    function(entry) {
                        //存在操作，取本地
                        console.log('[信息]本地存在音乐文件', savedFilePath)
                        resolve(savedFilePath)
                    },
                    function(e) {
                        console.log('[信息]无本地文件', savedFilePath, e)
                        let url = _this.$config.host + '/webapi/' + api.path + '?'
                        for (let key in params) {
                            url += key + '=' + params[key] + '&'
                        }
                        url = url.substr(0, url.length - 1)
                        uni.downloadFile({
                            url: url,
                            filePath: musicName,
                            header: {
                                'X-SYNO-TOKEN': _this.$config.synotoken,
                                'Cookie': _this.$config.cookie,
                            },
                            success: (res) => {
                                if (res.statusCode === 200) {
                                    console.log('下载成功' + musicName, res);
                                    // resolve(res.tempFilePath)
                                    // 拿到临时文件的绝对路径
                                    uni.saveFile({
                                        tempFilePath: res.tempFilePath,
                                        success: function(res2) {
                                            let filepaths = plus.io.convertLocalFileSystemURL(res2.savedFilePath);
                                            console.log('保存成功', res2, filepaths)
                                            // 通过这个路径来拿到他
                                            plus.io.resolveLocalFileSystemURL(filepaths,function(entry){
                                                const tempFileName = entry.name;
                                                entry.getParent(function (parentDicEntry) {
                                                    //保存音乐的地址
                                                    let savedFilePath = parentDicEntry.fullPath + '/' + musicName;
                                                    console.log('[信息]音乐保存路径',savedFilePath)
                                                    entry.moveTo({ fullPath: parentDicEntry.fullPath + '/'},musicName,
                                                    function (newFile) {
                                                      uni.setStorageSync(key + musicId,
                                                          savedFilePath);
                                                      resolve(savedFilePath)
                                                    },function(error){
                                                        console.error('保存失败', error)
                                                        reject(error.message)
                                                    })
                                                })
                                            })
                                        },
                                        fail: function(error) {
                                            console.error('保存失败', error)
                                            reject(error.message)
                                        }
                                    });
                                }else{
                                    reject('下载连接失败')
                                }
                            },
                            fail: (error) => {
                                console.error(error)
                                reject(error.message)
                            }
                        });
                    }
                );
                // #endif
            })
        }
    }

/**
     * 获取音乐封面
     * @param {Object} musicId
     */
    Vue.prototype.$getArtistCoverUrl = async function(artistName) {
        const apiName = 'SYNO.AudioStation.Cover'
        const api = this.$config.api[apiName]
        const key = 'loadArtistCoverImage:'
        if (api) {
            let url = '/webapi/' + api.path +
                '?api=' + apiName +
                '&artist_name=' + artistName +
                '&_dc=' + new Date().getTime();
            return new Promise((resolve, reject) => {
                const coverImg = uni.getStorageSync(key + artistName)
                if (coverImg) {
                    try {
                        setTimeout(function() {
                            // console.debug('[信息]发现缓存图片', musicId, coverImg.length)
                            resolve(coverImg)
                        }, 0)
                        return
                    } catch (e) {
                        // reject(e)
                        console.warn(musicId, coverImg, e)
                    }
                }
                uni.request({
                    url: this.$config.host + url,
                    data: {
                        _sid: this.$config.sid,
                        api: apiName,
                        output_default: true,
                        is_hr: false,
                        version: 3,
                        library: 'shared',
                        method: 'getcover',
                        view: 'default',
                        artist_name: artistName,
                        Synotoken: this.$config.synotoken,
                    },
                    header: {
                        'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
                        'X-SYNO-HASH': 'uniapp',
                        'X-SYNO-TOKEN': this.$config.synotoken,
                        // #ifndef H5
                        'Cookie': this.$config.cookie,
                        // #endif
                    },
                    responseType: 'arraybuffer',
                    method: "POST",
                    success: (response) => {
                        // console.log('[信息]', response.header['content-type'], response)
                        if (response.statusCode === 200) {

                            // console.log(img, url)
                            // #ifdef APP
                            const base64 = 'data:' + response.header['content-type'] +
                                ';base64,' + uni
                                .arrayBufferToBase64(response.data);
                            uni.setStorageSync(key + artistName, base64);
                            // console.debug('[信息]加载在线图片', artistName)
                            resolve(base64)
                            return
                            // #endif
                            // #ifdef H5
                            const img = new Blob([response.data], {
                                type: response.header['content-type']
                            })
                            const url = URL.createObjectURL(img);
                            let binary = '';
                            let bytes = new Uint8Array(response.data);
                            for (let i = 0; i < bytes.byteLength; i++) {
                                binary += String.fromCharCode(bytes[i]);
                            }
                            const base64 = 'data:' + response.header['content-type'] +
                                ';base64,' + window.btoa(
                                    binary);
                            //h5上使用缓存会导致localStrong很快占满
                            // uni.setStorageSync(key + musicId, base64);
                            // console.debug('[信息]加载在线图片', musicId)
                            resolve(url)
                            // #endif

                        } else {
                            reject(response)
                        }
                    },
                    fail: (error) => {
                        console.error('[错误]图片加载错误', error)
                    },
                });
            })
        } else {
            return ''
        }
    }


    /**
     * 群晖post封装
     * @param {Object} url
     * @param {Object} data
     */
    Vue.prototype.$post = function(url, data) {
        let _this = this;
        // #ifdef H5
        if (this.$config.sid) {
            if (!data) {
                data = {}
            }
            data._sid = this.$config.sid
        }
        // #endif
        return new Promise((resolve, reject) => {
            uni.request({
                url: this.$config.host + url,
                data: data,
                header: {
                    'Accept': 'application/json',
                    'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
                    'X-SYNO-HASH': 'uniapp',
                    'X-SYNO-TOKEN': this.$config.synotoken,
                    // #ifndef H5
                    'Cookie': this.$config.cookie,
                    // #endif
                },
                method: "POST",
                success: (response) => {
                    if (response.statusCode === 200) {
                        if (response.data.success == false && response.data.error.code ==
                            105) {
                            //请重新登录
                            _this.$clearLoginInfo()
                            console.log('[信息]请重新登录', data, {
                                url: _this.$config.host + url,
                                synotoken: _this.$config.synotoken,
                                cookie: _this.$config.cookie,
                                sid: _this.$config.sid
                            })
                            uni.reLaunch({
                                url: '/pages/login/index?statusCode=401'
                            })
                        }
                        // if (response.header) {
                        //     console.log('[信息]请求头', response.header)
                        // }
                        resolve(response.data)
                    } else {
                        reject(response)
                    }
                },
                fail: (error) => {
                    if (error && error.response) {
                        reject(error.response)
                        showError(error.response);
                    }
                },
            });
        })
    }

    /**
     * 获取cookies
     */
    Vue.prototype.$getCookies = function(key) {
        if (this.$config.cookie) {
            const cookieArr = this.$config.cookie.split(';')
            for (let i = 0; i < cookieArr.length; i++) {
                if (cookieArr[i].indexOf('=') != -1) {
                    const cookieKey = cookieArr[i].substr(0, cookieArr[i].indexOf('='))
                    const cookieValue = cookieArr[i].substr(cookieArr[i].indexOf('=') + 1)
                    if (key == cookieKey) {
                        return cookieValue
                    }
                } else {
                    if (key == cookieArr[i]) {
                        return cookieArr[i];
                    }
                }
            }
        }
    }

    /**
     * 获取转换播放歌曲信息
     * @param {Object} val
     */
    Vue.prototype.$getPlayData = async function(val) {
        this.$cache.loadMusicId = val.id
        this.$forceUpdate()
        let fileName = null
        try {
            fileName = val.path.substr(val.path.lastIndexOf('/') + 1)
        } catch (e) {
            console.warn(e)
        }
        let src = val.src;

        if (!src) {
            src = await this.$getMusicUrl(val.id, fileName);
        }

        const playData = {
            src: src,
            title: val.title,
            singer: fileName,
            coverImgUrl: val.cover,
            id: val.id,
            _data: val
        }
        if (val.additional && val.additional.song_tag && val.additional.song_tag.artist) {
            playData.artist = val.additional.song_tag.artist
        }
        this.$cache.loadMusicId = null
        return playData;
    }

    /**
     * 懒加载图片
     * @param {Object} data
     * @param {Object} item
     */
    Vue.prototype.$lazyLoadImage = function(data, item) {
        // console.log('[信息]图片加载完成', data, item)
        if (!item.lazyLoad) {
            this.$getMusicCoverUrl(item.id).then(cover => {
                item.cover = cover
                item.lazyLoad = true
                this.$forceUpdate()
            })
        }
    }

}
